<template>
  <div>
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商家名称">
          <el-input v-model="searchForm.name" placeholder="请输入商家名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="operation-serviceRegion">
      <el-button type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i> 新增商家
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-card>
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="name" label="商家名称" width="180"></el-table-column>
        <el-table-column prop="address" label="商家地址" width="120"></el-table-column>
        <el-table-column prop="logo" label="商家logo" width="120">
          <template slot-scope="scope">
            <el-image
                style="width: 80px; height: 80px"
                :src="scope.row.logo"
                :preview-src-list="fileList"
                fit="cover"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="productCount" label="商品信息" min-width="200">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.productRecords" :key="index">
              <span style="font-weight: bold">名称:</span>{{ item.name }}
              <span style="font-weight: bold">库存:</span>{{ item.stock }}
              <span style="font-weight: bold">¥ :</span>{{ item.salePrice }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="serviceAreas" label="关联服务区域" width="150"></el-table-column>
        <el-table-column prop="contactPerson" label="联系人" width="150"></el-table-column>
        <el-table-column prop="contactInfo" label="联系方式" width="150"></el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"
                         :formatter="(row,col) => formatTime(row[col.property])"></el-table-column>
        <el-table-column prop="updatedAt" label="最近更新时间" width="180"
                         :formatter="(row,col) => formatTime(row[col.property])"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === true ? 'success' : 'danger'">
              {{ scope.row.status === true ? '营业中' : '暂停营业' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template slot-scope="scope">
            <el-button
                size="mini"
                :type="scope.row.status === false ? 'success' : 'danger' "
                @click="updateStatus(scope.row)"
            >{{ scope.row.status === false ? '开启营业' : '暂停营业' }}
            </el-button>
<!--            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">服务点位管理</el-button>-->
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          class="pagination"
      ></el-pagination>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="50%"
        @close="resetForm"
    >
      <el-form
          :model="formData"
          :rules="rules"
          ref="formRef"
          label-width="120px"
      >
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="formData.address"></el-input>
        </el-form-item>
        <el-form-item label="商家LOGO" prop="logo">
          <el-upload
              action="#"
              list-type="picture-card"
              :auto-upload="false"
              :limit="2"
              :file-list="fileList"
              :on-change="handleChange"
              :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-button style="margin-top: 2px" @click="submitUpload">上传到OSS</el-button>
        </el-form-item>
        <el-form-item label="关联服务区域" prop="scenicSpotIds">
          <el-select
              v-model="formData.scenicSpotIds"
              multiple
              filterable
              remote
              style="width:100%"
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="remoteMethod"
              :loading="loading">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="formData.contactPerson"></el-input>
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactInfo">
          <el-input v-model="formData.contactInfo"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">营业中</el-radio>
            <el-radio :label="0">暂停营业</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getInfo, add, update, updateStatus} from '@/api/merchant'
import {getIdAndName} from '@/api/serviceArea'
import moment from 'moment';

export default {
  data() {
    return {

      fileList: [],
      options: [],
      list: [],
      loading: false,
      searchForm: {
        name: '',
        contactPerson: '',
        status: ''
      },
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增商家',
      formData: {
        scenicSpotIds: [],
        id: '',
        name: '',
        address: '',
        logo: '',
        contactPerson: '',
        contactInfo: '',
        status: 1,
        scenicSpotId: ''
      },
      rules: {
        name: [{required: true, message: '请输入商家名称', trigger: 'blur'}],
        scenicSpotIds: [
          {
            required: true,
            message: '请至少选择一个关联服务区域',
            trigger: 'blur'
          }
        ],
        logo: [{required: true, message: '请选择商家logo', trigger: 'blur'}],
        address: [{required: true, message: '请输入详情地址', trigger: 'blur'}],
        contactPerson: [{required: true, message: '请输入负责人', trigger: 'blur'}],
        contactInfo: [{required: true, message: '请输入联系方式', trigger: 'blur'}]
      }
    }
  },
  created() {
    this.fetchData()
  },
  mounted() {
  },
  methods: {
    handleChange(file, fileList) {
      console.log(21212)
      if (fileList.length > 1) {
        this.fileList = [fileList[fileList.length - 1]]
      } else {
        this.fileList = fileList
      }


    },
    handleRemove() {
      this.fileList = []
    },
    remoteMethod(query) {
      console.log(1212)
      if (query !== '') {
        getIdAndName(query).then(res => {
          console.log(res)
          this.options = res.data

        }).catch(() => {
        })
      } else {
        this.options = [];
      }
    },
    formatTime(date) {
      console.log(date)
      return moment(date).format('YYYY-MM-DD HH:mm:ss');
    },
    fetchData() {
      this.loading = true
      getInfo(this.pagination.currentPage, this.pagination.pageSize, this.searchForm).then(res => {
        // login(this.formData).then(res => {
        console.log(res)
        this.loading = false
        if (res.code === 200) {
          this.pagination.total = res.data.total
          this.tableData = res.data.recordList
        }
        // 处理登录成功逻辑
      }).catch(err => {
        this.loading = false
        console.log(err)
        // 错误已在拦截器统一处理
      })
    },
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm = {
        serviceRegion: '',
        contactPerson: '',
        status: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.fetchData()
    },
    handleAdd() {
      this.dialogTitle = '新增商家'
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑商家'
      this.formData = JSON.parse(JSON.stringify(row))
      this.options = [{id: row.serviceAreasId, name: row.serviceAreas}]
      this.formData.scenicSpotIds=row.serviceAreasId
      this.dialogVisible = true
    },
    handleDelete() {
      this.$confirm('确认删除该商家吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.fetchData()
      }).catch(() => {
      })
    },
    async submitUpload() {
      let _this = this
      console.log(212)
      const formData = new FormData();
      this.fileList.forEach(file => {
        formData.append('files', file.raw);
      });
      formData.append('bucketName', 'public-uav-img');
      try {
        const res = await this.$http.post(process.env.VUE_APP_BASE_API + '/sys/oss/upload', formData, {
          headers: {'Content-Type': 'multipart/form-data'}
        });
        if (res.status === 200) {
          _this.formData.logo = res.data
          console.log(res.data)
          this.$message.success('上传成功');
        }

      } catch (error) {
        console.log(error)
        this.$message.error('上传失败');
      }
    },
    updateStatus(row) {
      updateStatus({id: row.id}).then(res => {
        if (res.code === 200) {
          console.log(res)
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.dialogVisible = false
          this.fetchData()
        }
      })
    },
    submitForm() {
      this.formData.scenicSpotId = this.formData.scenicSpotIds[0]
      console.log(this.formData)
      this.$refs.formRef.validate(valid => {
        if (valid) {
          //上传图片
          let id = this.formData.id
          if (id !== undefined && id !== '') {
            update(this.formData).then(res => {
              if (res.code === 200) {
                console.log(res)
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.fetchData()
              }
            })
          } else {

            //上传图片

            add(this.formData).then(res => {
              if (res.code === 200) {
                console.log(res)
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.dialogVisible = false
                this.fetchData()
              }

            })
          }


        }
      })
    },
    resetForm() {
      this.fileList = []
      this.$refs.formRef.resetFields()
      this.formData = {
        id: '',
        serviceRegion: '',
        address: '',
        logo: '',
        contactPerson: '',
        contactInfo: '',
        status: 1
      }
    }
  }
}
</script>

<style scoped>
.service-serviceRegion-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-top: 10px;
}

.operation-serviceRegion {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
